//
//  JGHomeCollectionViewController.m
//  JGMeiTuanHD
//
//  Created by mac on 15/9/7.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGHomeCollectionViewController.h"
#import "JGConst.h"
#import "JGDeal.h"
#import "MJExtension.h"

#import "UIBarButtonItem+Extension.h"
#import "UIView+Extension.h"

#import "JGHomeTopItem.h"

#import "JGCategoryViewController.h"
#import "JGRegionViewController.h"

#import "JGMetaTool.h"
#import "JGCity.h"
#import "JGSort.h"
#import "JGRegion.h"
#import "JGCategory.h"
#import "JGSortViewController.h"
#import "MJRefresh.h"
#import "AwesomeMenu.h"
#import "UIView+AutoLayout.h"
#import "JGSelectedCityTool.h"
#import "JGDPRequestTool.h"

#import "JGSearchViewController.h"
#import "JGCollectViewController.h"
#import "JGRecentViewController.h"
#import "JGNavigationController.h"
#import "MBProgressHUD+MJ.h"
#import "JGMapViewController.h"
#import "JGCityViewController.h"

@interface JGHomeCollectionViewController ()<AwesomeMenuDelegate>

/** 分类item */
@property (nonatomic, weak) UIBarButtonItem *categoryItem;
/** 地区item */
@property (nonatomic, weak) UIBarButtonItem *regionItem;
/** 排序item */
@property (nonatomic, weak) UIBarButtonItem *sortItem;

/** 分类popover */
@property (nonatomic, strong) UIPopoverController *categoryPopover;
/** 区域popover */
@property (nonatomic, strong) UIPopoverController *regionPopover;
/** 排序popover */
@property (nonatomic, strong) UIPopoverController *sortPopover;

/** 当前选中的城市名字 */
@property (nonatomic, copy) NSString *selectedCityName;
/** 当前选中的分类名字 */
@property (nonatomic, copy) NSString *selectedCategoryName;
/** 当前选中的区域名字 */
@property (nonatomic, copy) NSString *selectedRegionName;
/** 当前选中的排序 */
@property (nonatomic, strong) JGSort *selectedSort;

/** 记录当前页码 */
@property (nonatomic, assign) int  currentPage;
/** 总数 */
@property (nonatomic, assign) int  totalCount;

@end

@implementation JGHomeCollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏内容
    [self setupLeftNav];
    [self setupRightNav];
    
    // 创建awesomemenu
    [self setupAwesomeMenu];
    
    // 添加上拉刷新
    [self.collectionView addFooterWithTarget:self action:@selector(loadMoreDeals)];
    [self.collectionView addHeaderWithTarget:self action:@selector(loadNewDeals)];
}

#pragma mark - 通知处理
/** 监听通知 */
- (void)setupNotifications
{
    // 监听城市改变
    [JGNotificationCenter addObserver:self selector:@selector(cityDidChange:) name:JGCityDidChangeNotification object:nil];
    // 监听排序改变
    [JGNotificationCenter addObserver:self selector:@selector(sortDidChange:) name:JGSortDidChangeNotification object:nil];
    // 监听分类改变
    [JGNotificationCenter addObserver:self selector:@selector(categoryDidChange:) name:JGCategoryDidChangeNotification object:nil];
    // 监听区域改变
    [JGNotificationCenter addObserver:self selector:@selector(regionDidChange:) name:JGRegionDidChangeNotification object:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setupNotifications];
    
    //没有选择城市时，直接进入到城市选择页面
    if ([JGSelectedCityTool selectedCityMessage] == nil) {
        JGCityViewController *city = [[JGCityViewController alloc] init];
        JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:city];
        nav.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        [self.collectionView headerBeginRefreshing];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [JGNotificationCenter removeObserver:self];;
}

- (void)setupAwesomeMenu
{
    // 1.中间的item
    AwesomeMenuItem *startItem = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"icon_pathMenu_background_normal"] highlightedImage:[UIImage imageNamed:@"icon_pathMenu_background_highlighted"] ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_highlighted"]];
    startItem.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"icon_pathMenu_background"]];
    
    // 2.周边的item
    AwesomeMenuItem *item0 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_mine_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_mine_highlighted"]];
    AwesomeMenuItem *item1 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    AwesomeMenuItem *item2 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_scan_highlighted"]];
    AwesomeMenuItem *item3 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_more_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_more_highlighted"]];
    
    NSArray *items = @[item0, item1, item2, item3];
    AwesomeMenu *menu = [[AwesomeMenu alloc] initWithFrame:CGRectZero startItem:startItem optionMenus:items];
    menu.alpha = 0.5;
    // 设置菜单的活动范围
    menu.menuWholeAngle = M_PI_2;
    // 设置开始按钮的位置
    menu.startPoint = CGPointMake(50, 150);
    // 设置代理
    menu.delegate = self;
    // 不要旋转中间按钮
    menu.rotateAddButton = NO;
    [self.view addSubview:menu];
    
    // 设置菜单永远在左下角
    [menu autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [menu autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
    [menu autoSetDimensionsToSize:CGSizeMake(200, 200)];
}

#pragma mark - AwesomeMenuDelegate
- (void)awesomeMenuWillAnimateOpen:(AwesomeMenu *)menu
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_cross_normal"];
    
    // 完全显示
    menu.alpha = 1.0;
}

- (void)awesomeMenuWillAnimateClose:(AwesomeMenu *)menu
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    // 半透明显示
    menu.alpha = 0.4;
}

- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    // 半透明显示
    menu.alpha = 0.4;
    switch (idx) {
        case 1: { // 收藏
            JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:[[JGCollectViewController alloc] init]];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
            
        case 2: { // 最近访问记录
            JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:[[JGRecentViewController alloc] init]];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - 监听通知
-(void)cityDidChange:(NSNotification *)notification // 得到一个城市名字传给区域
{
    self.selectedCityName = notification.userInfo[JGSelectCityName];
    //写入沙盒
    [JGSelectedCityTool addSelectedCityMessage:@{
                                                 @"selectCityName" : self.selectedCityName,
                                                 @"selectedRegionName" : @"",
                                                 @"regioName" : @"全部",
                                                 @"subtitle" : @"全城"
                                                 }];
    
//    self.selectedCategoryName = nil;
    self.selectedRegionName = nil;
//    self.selectedSort = nil;
    
    // 1.更换顶部区域item的文字
    JGHomeTopItem *topItem = (JGHomeTopItem *)self.regionItem.customView;
    [topItem setTitle:[NSString stringWithFormat:@"%@ - 全部", self.selectedCityName]];
    [topItem setSubtitle:@"全城"];
    
    // 2.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}


- (void)categoryDidChange:(NSNotification *)notification
{
    JGCategory *category = notification.userInfo[JGSelectCategory];
    NSString *subcategoryName = notification.userInfo[JGSelectSubcategoryName];
    
    if (subcategoryName == nil || [subcategoryName isEqualToString:@"全部"]) {
        self.selectedCategoryName = category.name;
    } else {
        self.selectedCategoryName = subcategoryName;
    }
    
    if ([self.selectedCategoryName isEqualToString:@"全部分类"]) { // 主表格中
        self.selectedCategoryName = nil;
    }
    
    // 1.更换顶部item的文字
    JGHomeTopItem *topItem = (JGHomeTopItem *)self.categoryItem.customView;
    [topItem setIcon:category.icon highIcon:category.highlighted_icon];
    [topItem setTitle:category.name];
    [topItem setSubtitle:subcategoryName];
    
    // 2.关闭popover
     [self.categoryPopover dismissPopoverAnimated:YES];
    
    // 2.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}

- (void)regionDidChange:(NSNotification *)notification
{
    JGRegion *region = notification.userInfo[JGSelectRegion];
    NSString *subregionName = notification.userInfo[JGSelectSubregionName];
    
    if (subregionName == nil || [subregionName isEqualToString:@"全部"]) {
        self.selectedRegionName = region.name;
    } else {
        self.selectedRegionName = subregionName;
    }
    
    if ([self.selectedRegionName isEqualToString:@"全部"]) {
        self.selectedRegionName = @"";
    }
    
    // 1.更换顶部item的文字
    //从沙盒里面取出
    NSDictionary *dict = [JGSelectedCityTool selectedCityMessage];
    NSLog(@"%@", dict[@"selectCityName"]);
    JGHomeTopItem *topItem = (JGHomeTopItem *)self.regionItem.customView;
    [topItem setTitle:[NSString stringWithFormat:@"%@ - %@", dict[@"selectCityName"], region.name]];
    [topItem setSubtitle:subregionName];
    
    //写入沙盒
    [JGSelectedCityTool addSelectedCityMessage:@{
                                                 @"selectCityName" : dict[@"selectCityName"],
                                                 @"selectedRegionName" : self.selectedRegionName,
                                                 @"regioName" : region.name,
                                                 @"subtitle" : (subregionName == nil)? @"" : subregionName
                                                 }];
    
    // 2.关闭popover
    [self.regionPopover dismissPopoverAnimated:YES];
    
    // 2.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}

- (void)sortDidChange:(NSNotification *)notification
{
    self.selectedSort = notification.userInfo[JGSelectSort];
    
    // 1.更换顶部排序item的文字
    JGHomeTopItem *topItem = (JGHomeTopItem *)self.sortItem.customView;
    [topItem setSubtitle:self.selectedSort.label];
    
    // 2.关闭popover
    [self.sortPopover dismissPopoverAnimated:YES];
    
    // 2.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}


#pragma mark - 跟服务器交互
- (void)loadDeals
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    // 调用子类实现的方法
    NSDictionary *dict = [JGSelectedCityTool selectedCityMessage];
    // 每页的条数
    params[@"limit"] = @30;
    // 页码
    params[@"page"] = @(self.currentPage);
    
    params[@"city"] = dict[@"selectCityName"];
    // 分类(类别)
    if (self.selectedCategoryName) {
        params[@"category"] = self.selectedCategoryName;
    }
    // 区域
    if (![dict[@"selectedRegionName"] isEqualToString:@""]) {
        params[@"region"] = dict[@"selectedRegionName"];
    }
    // 排序
    if (self.selectedSort) {
        params[@"sort"] = @(self.selectedSort.value);
    }

    NSLog(@"%@", params);
    
    __weak typeof(self) weakSelf = self;
    [[JGDPRequestTool sharedAPITool] request:@"v1/deal/find_deals" params:params success:^(id json) {
        weakSelf.totalCount = [json[@"total_count"] intValue];
        
        // 1.取出团购的字典数组
        NSArray *newDeals = [JGDeal objectArrayWithKeyValuesArray:json[@"deals"]];
        
        if (weakSelf.currentPage == 1) { // 清除之前的旧数据
            [weakSelf.deals removeAllObjects];
        }
        
        [weakSelf.deals addObjectsFromArray:newDeals];
        
        // 2.刷新表格
        [weakSelf.collectionView reloadData];
        
        // 3.结束上拉加载
        [weakSelf.collectionView headerEndRefreshing];
        [weakSelf.collectionView footerEndRefreshing];
        
    } failure:^(NSError *error) {
        // 1.提醒失败
        [MBProgressHUD showError:@"网络繁忙,请稍后再试" toView:self.view];
        
        // 2.结束刷新
        [weakSelf.collectionView headerEndRefreshing];
        [weakSelf.collectionView footerEndRefreshing];
        
        // 3.如果是上拉加载失败了
        if (weakSelf.currentPage > 1) {
            weakSelf.currentPage--;
        }
        
    }];
    
}

//上啦刷新
- (void)loadMoreDeals
{
    self.currentPage ++; //改变page而已
    
    [self loadDeals];
}

//刚开始加载或者更换了条件（城市）时,后者下拉
- (void)loadNewDeals
{
    self.currentPage = 1;
    
    [self loadDeals];
}

#pragma mark - 设置导航栏内容
- (void)setupLeftNav
{
    // 1.LOGO
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_meituan_logo"] style:UIBarButtonItemStylePlain target:nil action:nil];
    logoItem.enabled = NO;
    
    // 2.类别
    JGHomeTopItem *categoryTopItem = [JGHomeTopItem item];
    [categoryTopItem setIcon:@"btn_changeCity" highIcon:@"btn_changeCity_selected"];
    [categoryTopItem addTarget:self action:@selector(categoryClick)];
    [categoryTopItem setTitle:@"美团"];
    [categoryTopItem setSubtitle:@"全部分类"];
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryTopItem];
    self.categoryItem = categoryItem;
    
    // 3.地区
    JGHomeTopItem *regionItem = [JGHomeTopItem item];
    [regionItem setIcon:@"icon_district" highIcon:@"icon_district_highlighted"];
    [regionItem addTarget:self action:@selector(regionClick)];
    
    if ([JGSelectedCityTool selectedCityMessage] !=nil) {
         NSDictionary *dict = [JGSelectedCityTool selectedCityMessage];
        [regionItem setTitle:[NSString stringWithFormat:@"%@ - %@", dict[@"selectCityName"], dict[@"regioName"]]];
        [regionItem setSubtitle:dict[@"subtitle"]];
    }
    UIBarButtonItem *districtItem = [[UIBarButtonItem alloc] initWithCustomView:regionItem];
    self.regionItem = districtItem;
    
    // 4.排序
    JGHomeTopItem *sortTopItem = [JGHomeTopItem item];
    [sortTopItem setIcon:@"icon_sort" highIcon:@"icon_sort_highlighted"];
    [sortTopItem addTarget:self action:@selector(sortClick)];
    [sortTopItem setTitle:@"筛选"];
    [sortTopItem setSubtitle:@"默认排序"];
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithCustomView:sortTopItem];
    self.sortItem = sortItem;
    
    self.navigationItem.leftBarButtonItems = @[logoItem, categoryItem, districtItem, sortItem];
}

- (void)setupRightNav
{
    UIBarButtonItem *mapItem = [UIBarButtonItem itemWithTarget:self action:@selector(map)  image:@"icon_map" highImage:@"icon_map_highlighted"];
    mapItem.customView.width = 60;
    
    UIBarButtonItem *searchItem = [UIBarButtonItem itemWithTarget:self action:@selector(search) image:@"icon_search" highImage:@"icon_search_highlighted"];
    searchItem.customView.width = 60;
    self.navigationItem.rightBarButtonItems = @[mapItem, searchItem];
}

#pragma mark - 顶部item点击方法
- (void)map
{
    JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:[[JGMapViewController alloc] init]];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)search
{
    if ([JGSelectedCityTool selectedCityMessage] !=nil) {
        NSDictionary *dict = [JGSelectedCityTool selectedCityMessage];
        JGSearchViewController *searchVC = [[JGSearchViewController alloc] init];
        searchVC.cityName = dict[@"selectCityName"];
        JGNavigationController *nav = [[JGNavigationController alloc] initWithRootViewController:searchVC];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        [MBProgressHUD showError:@"请选择城市" toView:self.view];
    }
}

- (void)categoryClick
{
    // 显示分类菜单
   self.categoryPopover = [[UIPopoverController alloc] initWithContentViewController:[[JGCategoryViewController alloc]init]];
    [self.categoryPopover presentPopoverFromBarButtonItem:self.categoryItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)regionClick
{
    // 显示区域菜单
    JGRegionViewController *region = [[JGRegionViewController alloc] init];
    
    if ([JGSelectedCityTool selectedCityMessage] !=nil) {
        NSDictionary *dict = [JGSelectedCityTool selectedCityMessage];
        JGCity *city = [[[JGMetaTool cities] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", dict[@"selectCityName"]]] firstObject];
        region.regions = city.regions;
    }
 
    // 显示区域菜单
    self.regionPopover = [[UIPopoverController alloc] initWithContentViewController:region];
    [self.regionPopover presentPopoverFromBarButtonItem:self.regionItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    
    region.popover = self.regionPopover;
}

- (void)sortClick
{
    // 显示排序菜单
    self.sortPopover = [[UIPopoverController alloc] initWithContentViewController:[[JGSortViewController alloc] init]];
    [self.sortPopover presentPopoverFromBarButtonItem:self.sortItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark - 数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // 尾部控件的可见性
    self.collectionView.footerHidden = (self.deals.count == self.totalCount);
    return [super collectionView:collectionView numberOfItemsInSection:section];
}

#pragma mark - 实现父类方法
- (NSString *)emptyIcon
{
    return @"icon_deals_empty";
}
@end
